package org.jinyan.led.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器套接字工厂
 * 
 * @version 1.0
 */
public class ServerSocketFactory {
	private static ServerSocket server;
	private static Socket client;
	private boolean ifRunServer = true;

	public void runServer(int port) throws IOException {
		// 本地建立一个套接字服务器，等待其他机器访问
		server = new ServerSocket(port);
		System.out.println("Socket Server Start...");
		new ServerThread();
	}

	class ServerThread implements Runnable {
		Thread t;

		public ServerThread() {
			t = new Thread(this);
			t.start();
		}

		public void run() {
			try {
				while (ifRunServer) {
					if (client == null) {
						client = server.accept();
					}

					if (client != null) {
						InputStream input = client.getInputStream();
						System.out.println("客户端："
								+ client.getLocalSocketAddress());
						// getMessage();
					}
					Thread.sleep(1000);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void stopThread() {
			try {
				ifRunServer = false;
				this.t.join(100);
			} catch (InterruptedException ex) {
				System.out.println("socket服务器线程终止异常！！！");
			} finally {
				t = null;
			}
		}
	}
}
